
import sys
from theconfig import *
from readfasta import PadSequence
from indexing import featureindex

def _chromosomeIndex(chr):
    #return featureindex.FeatureIndex(GENOME_DIR + "/" + chr + ".fasta-features.INDEX")
    return featureindex.FeatureIndex(GENOME_DIR + "/" + chr + ".fa.INDEX")

def readGenomicSequence(query, returnAsFasta=False, fastaLineLength=60, pad=PadSequence.BOTH):
    '''
    '''
    (chr, spos, epos) = query
    spos = long(spos)
    epos = long(epos)
    
    padLeft = pad & PadSequence.LEFT
    padRight = pad & PadSequence.RIGHT
    firstPos = spos
    lastPos = epos
    ret = ""

    if padLeft:
        while spos<=0:
            spos += 1
            ret += "N"
    else:
        if spos<=0:
            spos = 1
            firstPos = 1

    pos = spos
    for feature in _chromosomeIndex(chr).getFeatures(query):
        details = feature.getDetails()
        seq = details.seq
        pos = feature.spos
        if pos > epos:
            break
        elif pos + len(seq) > spos:
            ret += seq[max(0, spos-pos) : epos-pos+1].upper()
            pos += len(seq)
    
    if padRight:
        while pos<=epos:
            pos += 1
            ret += "N"
    else:
        if pos<=epos:
            lastPos = pos-1
            
    if not returnAsFasta:
        return ret

    rng = "[%d,%d]" % (firstPos, lastPos)
    fasta = [">%s%s" % (chr, rng)]
    for i in xrange(0, len(ret), fastaLineLength):
        fasta.append(ret[i:i+fastaLineLength])
    return fasta

def printUsage(args, usage, minArgs=2):
  if len(args) < minArgs or args[1].startswith("-h") or args[1].startswith("--h"):
    print usage
    sys.exit(1)

usageString = """
Usage: python %s CHR MIN_POS MAX_POS [-F]

Prints out the bases at positions [MIN_POS, MAX_POS] from
the specified FASTA file.  If -F is specified, return result
in FASTA format.
"""

if __name__=="__main__":
    printUsage(sys.argv, usageString % sys.argv[0], 4)
    query = (sys.argv[1], long(sys.argv[2]), long(sys.argv[3]))
    if len(sys.argv)>4 and sys.argv[4]=="-F":
        fasta = readGenomicSequence(query, True)
        for line in fasta: print line
    else:
        print readGenomicSequence(query)

